package com.yuda.job.util;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class HttpClient {


	public static String connectPOST(String urlStr,String params) throws IOException {
		InputStream ins = null;
		try {
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");//POST
			conn.setConnectTimeout(1800000000);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			BufferedWriter ous = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
			ous.write(params);
			ous.flush();
			conn.connect();
			int code = conn.getResponseCode();
			if (code == HttpURLConnection.HTTP_OK || code == 400) {
				ins = conn.getInputStream();
				return readInputStream(ins);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} finally {
			if (ins != null) {
				ins.close();
			}
		}
		return null;
	}

	public static String connectGet(String urlStr) throws IOException {
		InputStream ins = null;
		try {
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(1800000000);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setReadTimeout(200000000);
			conn.connect();

			int code  = conn.getResponseCode();
			if (code == HttpURLConnection.HTTP_OK || code == 400) {
				ins = conn.getInputStream();
				return readInputStream(ins);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (java.net.SocketTimeoutException e) {
//			System.out.println("请忽略此错误信息");
		} finally {
			if (ins != null) {
				ins.close();
			}
		}
		return null;
	}


	public static String readInputStream(InputStream ins) {
		if (ins == null) {
			return null;
		}
		BufferedInputStream bis = new BufferedInputStream(ins);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			byte[] buffer = new byte[128];
			int n;
			while ((n = bis.read(buffer)) != -1) {
				bos.write(buffer, 0, n);
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return new String(bos.toByteArray());
	}

}
